<?php

class Curl {

	private $url;
	private $options = array();
	private $headers = array();
	private $useragent = "Mozilla/5.0 (Windows; Windows NT 5.1; en; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11";

	function __construct( $url = '' ) {
		
		if ( !function_exists( 'curl_init' ) ) {
			error_log( 'The curl module is not enabled on php' );		
		}
	}

	public function post( $url, $params = null, $options = null ) {
		$querystring = null;

		if ( $this->validate( $url ) ) {
			if ( ! $options ) {
				$this->base_options();
				$options = $this->options;
			}

			if ( is_array( $params ) ) {
				$url .= $this->querystring( $params );
			}

			$ch  = curl_init( $url );
			curl_setopt( $ch, CURLOPT_POST, 1 );

			curl_setopt_array( $ch, $options );
			$results = curl_exec( $ch );
			return $results;
		}

		return false;
	}

	public function get( $url, $params = null, $options = null ) {
		$querystring = null;
	
                if ( $this->validate( $url ) ) {
			
                        if ( ! $options ) {
                                $this->base_options();
                                $options = $this->options;
                        }

                        if ( is_array( $params ) ) {
                                $url .= $this->querystring( $params );
                        }

                        $ch  = curl_init( $url );
                        curl_setopt( $ch, CURLOPT_HTTPGET, 1 );
                        curl_setopt_array( $ch, $options );
                        $results = curl_exec( $ch );

			// Check if any error occured
			if( curl_errno( $ch ) )
			{
				$results = new WikiError(  'Curl error: ' . curl_error( $ch ) );
			}

                        return $results;
                }

                return false;
	}

	public function base_options() {
		$this->set_option( CURLOPT_RETURNTRANSFER, 1 );
		$this->set_option( CURLOPT_FOLLOWLOCATION, false );
		$this->set_option( CURLOPT_USERAGENT, $this->useragent );
	}

	public function set_option( $opt, $val ) {
		$this->options[$opt] = $val;
	}

	public function validate( $url ) {
		if ( !preg_match( '!^\w+://! i', $url ) ) {
			error_log( $url . ' is an invalid url' );
			return false;
		}
		return true;
	}

	public function querystring ( $params ) {
		$querystring = null;
		$i = 0;
		foreach ( $params as $key => $val ) {
			if ( $i == 0 ) { 
				$querystring .= '?' . $key . '=' . $val;
			} else { 
				$querystring .= '&' . $key . '=' . $val;
			}
			$i++;
		}
		return $querystring;
	}
	
}

